package com.xian.handler;

import com.xian.service.RpcRequest;
import com.xian.service.UserServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 自定义业务处理器
 */
@Component
public class UserServiceHandler extends SimpleChannelInboundHandler<RpcRequest> implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    //客户端读取数据时，该方法会被调用


    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        this.channelRead0(ctx, (RpcRequest) msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcRequest request) throws Exception {
        //获取类名
        String className = request.getClassName();
        //以下两种途径都能正常执行得出结果

        //灵活
        //通过applicationContext获取service实现类
        Object serviceBean = applicationContext.getBean(className);
        //获取入参，并通过class.getMethod方法找到需要实际执行的方法
        Method method = serviceBean.getClass().getMethod(request.getMethodName(), request.getParameterTypes());
        //进行执行，写入返回结果
        channelHandlerContext.writeAndFlush(method.invoke(serviceBean, request.getParameters()));


        //客户端将来传递参数的时候回传度一个参数：UserService#sayHello#are you ok
        //1.判断请求规则
       /* if (msg.toString().startsWith("UserService")) {
            UserServiceImpl service = new UserServiceImpl();
            String result = service.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
            ctx.writeAndFlush(result);
        }*/

    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (this.applicationContext == null) {
            this.applicationContext = applicationContext;
        }
    }
}
